from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client

@deconstructible # 告知django使用重写后的方法

class FastDFSStorage(Storage):
    """
    {'Group name': 'group1',
    'Local file name': './1.jpg',
    'Remote file_id': 'group1/M00/00/00/wKhBgFw1yMKAN6w6AAQ8wuZRhIU704.jpg',
    'Status': 'Upload successed.',
    'Storage IP': '192.168.65.128',
    'Uploaded size': '271.00KB'}

    """

     # 初始化链接对象,配置文件中配置
    def __init__(self,client_conf=None,base_url=None):

        if client_conf is None:
            client_conf = settings.CLIENT_CONF
        self.client_conf = client_conf

        # 路径拼接
        if base_url is None:
            base_url = settings.BASE_URL
        self.base_url =  base_url

    def _open(self,name,mode='rb'):
        pass

    # 改写Storage保存业务逻辑
    def _save(self, name, content, max_length=None):

        # 生成fastdfs链接对象
        c = Fdfs_client(self.client_conf)

        # 文件上传 上传二进制数据  read读取操作
        status = c.upload_by_buffer(content.read())

        # 判断是否上传成功
        if status['Status'] != 'Upload successed.':
            raise Exception('upload errors')
         # 上传成功获取路径
        file_id = status['Remote file_id']
        return file_id

    # 拼接完整url路径
    # 路径存放在配置信息中
    def url(self, name):
        return self.base_url+name

    # 判断文件是否重复保存
    def exists(self, name):
        return False